<template>
  <div  class="login-box">
    <h1 style="color: tomato" >欢迎登陆</h1>

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码：" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="login('ruleForm')">登陆</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>

export default {
  name: 'Login',
  data () {
    return {
      ruleForm: {
       username: '',
        password: '',

      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
        ],

        password: [
          {required: true, message: '请输入用户密码', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
        ],
      }
    }
  },

  methods: {
    login(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        let vm = this;
        if (valid) {
          //发送axios请求
          this.axios({
            method:"POST",
            url:"http://localhost:9090/user/login",
            data:{
              username:vm.ruleForm.username,
              password:vm.ruleForm.password
            },

          }).then(function (res){
            if (res.data.code==0){
              console.log(res)
              vm.$message({
                message: res.data.msg,
                type: 'success'
              });
              // 把用户信息放入store中，然后就可以在其他组件中获取用户信息了
              vm.$store.commit('updateUser', res.data.data);
              setTimeout(function () {
                vm.$router.push("/cardList")
              }, 1000);
            }else {
              vm.$message({
                message:res.data.msg,
                type:"error"
              });
            }
          });
        }else {
          //校验失败
          vm.$message.error('输入格式错误');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}


.login-box {
  width: 500px;
  height: 300px;
  border: 1px solid #DCDFE6;
  margin: 150px auto;
  padding: 20px 50px 20px 30px;
  border-radius: 20px;
  box-shadow: 0px 0px 20px #DCDFE6;
}
</style>
